<?php

/**
 * @Author: Wang Chunsheng 2192138785@qq.com
 * @Date:   2020-03-04 00:17:41
 * @Last Modified by:   Wang chunsheng  email:2192138785@qq.com
 * @Last Modified time: 2020-06-03 11:29:05
 */


namespace common\addons\diandi_shop\backend\order;

use Yii;
use common\addons\diandi_shop\services\OrderService;
use common\addons\diandi_shop\models\DdOrder;
use common\addons\diandi_shop\models\DdOrderAddress;
use common\addons\diandi_shop\models\DdOrderGoods;
use common\addons\diandi_shop\models\enums\OrderStatus;
use common\addons\diandi_shop\models\searchs\DdOrderSearch;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;
use backend\controllers\BaseController;
use common\helpers\ErrorsHelper;
use common\helpers\FileHelper;
use common\helpers\ImageHelper;
use common\helpers\LevelTplHelper;
use common\helpers\ResultHelper;
use common\models\DdCorePaylog;
use common\models\DdRegion;
use moxuandi\phpSpreadsheet\ExportData;
use moxuandi\phpSpreadsheet\ExportModel;
use yii\web\BadRequestHttpException;
use yii\web\HttpException;

/**
 * DdOrderController implements the CRUD actions for DdOrder model.
 */
class DdOrderController extends BaseController
{
    public $modelSearchName = 'DdOrderSearch';



    /**
     * {@inheritdoc}
     */
    public function behaviors()
    {
        $behaviors = parent::behaviors();
        $ips = Yii::$app->settings->get('DiandiShopStroe', 'Lodop_ip');
        $behaviors['corsFilter']['cors'] = [
            'http://'.$ips.':8000',
            'http://'.$ips.'18000',
        ]; 
            
        $behaviors['verbs'] =[
            'class' => VerbFilter::className(),
            'actions' => [
                'delete' => ['POST'],
            ],
        ];

        return $behaviors;
    }

    public function actions()
    {
        $actions=parent::actions();
        $actions['get-region']=[
            'class'=>\diandi\region\RegionAction::className(),
            'model'=>DdRegion::className()
        ];
        return $actions;
    }



    /**
     * Lists all DdOrder models.
     * @return mixed
     */
    public function actionIndex()
    {
        // $data = [
        //     ['id' => 1, 'name' => '张三', 'sex' => '男', 'phone' => 15515181929, 'idc' => 211325659536289526],
        //     ['id' => 2, 'name' => '李四', 'sex' => '男'],
        //     ['id' => 5, 'name' => '王二', 'sex' => '女'],
        //     ['id' => 8, 'name' => '麻子', 'sex' => '女'],
        // ];


        $searchModel = new DdOrderSearch();
        $dataProvider = $searchModel->search(Yii::$app->request->queryParams);

        // ExportModel::widget([
        //     'models' => DdOrder::find()->all(),  // 必须
        //     'asAttachment' => true,  // 默认值, 可忽略
        // ]);

        return $this->render('index', [
            'searchModel' => $searchModel,
            'dataProvider' => $dataProvider,
        ]);
    }

    /**
     * Displays a single DdOrder model.
     * @param integer $id
     * @return mixed
     * @throws NotFoundHttpException if the model cannot be found
     */
    public function actionView($id)
    {
        $detail = OrderService::detail($id);
        $address = DdOrderAddress::findOne(['order_id' => $id]);
        $region = new DdRegion();
        $Helper = new LevelTplHelper([
            'pid' => 'pid',
            'cid' => 'id',
            'title' => 'name',
            'model' => $region,
            'id' => 'id'
        ]);
        return $this->render('view', [
            'model' => $this->findModel($id),
            'detail' => $detail,
            'address' => $address,
            'Helper' => $Helper,
        ]);
    }

    // 修改订单收货地址
    public function actionUpaddress()
    {
        if (Yii::$app->request->isPost) {
            $data = Yii::$app->request->post();
            $DdOrderAddress = new DdOrderAddress();
            $datas = [
                'name' => $data['DdOrderAddress']['name'],
                'phone' => $data['DdOrderAddress']['phone'],
                'province_id' => $data['DdOrderAddress']['province_id'],
                'city_id' => $data['DdOrderAddress']['city_id'],
                'region_id' => $data['DdOrderAddress']['region_id'],
                'detail' => $data['DdOrderAddress']['detail']
            ];
            $order_id = $data['DdOrderAddress']['order_id'];
            if ($DdOrderAddress->updateAll($datas, ['order_id' => $order_id])) {
                return $this->redirect(['view', 'id' => $order_id]);
            } else {
                $message = ErrorsHelper::getModelError($DdOrderAddress);
                throw new BadRequestHttpException($message);
            }
        }
    }

    /**
     * Creates a new DdOrder model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     * @return mixed
     */
    public function actionCreate()
    {
        $model = new DdOrder();

        if ($model->load(Yii::$app->request->post()) && $model->save()) {
            return $this->redirect(['view', 'id' => $model->order_id]);
        }

        return $this->render('create', [
            'model' => $model,
        ]);
    }

    /**
     * Updates an existing DdOrder model.
     * If update is successful, the browser will be redirected to the 'view' page.
     * @param integer $id
     * @return mixed
     * @throws NotFoundHttpException if the model cannot be found
     */
    public function actionUpdate($id)
    {
        $model = $this->findModel($id);

        if ($model->load(Yii::$app->request->post()) && $model->save()) {
            return $this->redirect(['view', 'id' => $model->order_id]);
        }

        return $this->render('update', [
            'model' => $model,
        ]);
    }

    /**
     * Deletes an existing DdOrder model.
     * If deletion is successful, the browser will be redirected to the 'index' page.
     * @param integer $id
     * @return mixed
     * @throws NotFoundHttpException if the model cannot be found
     */
    public function actionDelete($id)
    {
        $this->findModel($id)->delete();

        return $this->redirect(['index']);
    }

    // 订单操作
    public function actionConfirm()
    {
        if (Yii::$app->request->isPost) {
            $data = Yii::$app->request->post();
            $ctype = $data['ctype'];
            $order_id = $data['order_id'];
            return OrderService::confirmOrder($order_id, $ctype);
        }
    }


    public function actionExportdata()
    {
        $ids = Yii::$app->request->get('ids');
        $id = explode(',',$ids);
        $model = DdOrder::find()->where(['order_id'=>$id])->with(['goods','address'])->all();
        
        if($model){
            $DdRegion = new DdRegion();
            $region = $DdRegion->find()->indexBy('id')->asArray()->all();
            
            foreach ($model as $key => &$value) {
                $value['create_time'] = date('Y-m-d H:i:s',$value['create_time']);
                $goods = '';
                if($value['goods']){
                    foreach ($value['goods'] as $k => $val) {
                        $goods .= $val['goods_name'].':'.$val['goods_price'].'*'.$val['total_num'].PHP_EOL;
                        
                    }
                }
                $value['goodsinfo'] = $goods;
                $value['address']['detail'] = $region[$value['address']['region_id']]['merger_name'].$value['address']['detail'];
            }
            
            ExportModel::widget([
                'models' =>$model,  // 必须
                'asAttachment' => true,  // 默认值, 可忽略
                'columns'=>[
                    'order_id','bloc_id','store_id','order_no','total_price','pay_price','pay_status','pay_time','express_price','express_company','express_no','delivery_status','delivery_time','receipt_status','receipt_time','order_status','transaction_id','user_id','remark','create_time','address.name','address.phone','address.detail','goodsinfo'
                ]
            ]);    
        }else{
             throw new HttpException(400,'没有可以导出的数据');
        }
        
    }

    public function actionPrints()
    {  
        if(Yii::$app->request->isPost){
            $ids = Yii::$app->request->post('ids');
            $list = OrderService::details($ids);
            
            $info = Yii::$app->settings->getAllBySection('DiandiShopStroe');
            $info['logo'] = ImageHelper::tomedia($info['logo']);
            $info['banner'] = ImageHelper::tomedia($info['banner']);
            $info['wxappName'] = Yii::$app->settings->get('Wxapp', 'name');
            $wxappHeadimg = Yii::$app->settings->get('Wxapp', 'headimg');
            $info['wxappHeadimg'] = ImageHelper::tomedia($wxappHeadimg);
            
            return ResultHelper::json(200,'打印数据请求成功',[
                'order'=>$list,
                'store'=>$info,
                'time'=>date('y-m-d',time())
                ]);
        }
        

    }


    public function actionDeletes()
    {
        if (Yii::$app->request->isPost) {
            $ids = Yii::$app->request->post('ids');
            $DdOrder = new DdOrder();
            $DdOrderGoods = new DdOrderGoods();
            $DdOrderAddress = new DdOrderAddress();

            $DdOrder::deleteAll(['order_id' => $ids]);
            $DdOrderGoods::deleteAll(['order_id' => $ids]);
            $DdOrderAddress::deleteAll(['order_id' => $ids]);

            if (ErrorsHelper::getModelError($DdOrder)) {
                $errors = ErrorsHelper::getModelError($DdOrder);
                return ResultHelper::json(401, '删除失败', $errors);
            }
            if (ErrorsHelper::getModelError($DdOrderGoods)) {
                $errors = ErrorsHelper::getModelError(DdOrderGoods::className());
                return ResultHelper::json(401, '删除失败', $errors);
            }
            if (ErrorsHelper::getModelError($DdOrderAddress)) {
                $errors = ErrorsHelper::getModelError($DdOrderAddress);
                return ResultHelper::json(401, '删除失败', $errors);
            }
            return ResultHelper::json(200, '删除成功', []);
        }
    }

    /**
     * Finds the DdOrder model based on its primary key value.
     * If the model is not found, a 404 HTTP exception will be thrown.
     * @param integer $id
     * @return DdOrder the loaded model
     * @throws NotFoundHttpException if the model cannot be found
     */
    protected function findModel($id)
    {
        if (($model = DdOrder::findOne($id)) !== null) {
            return $model;
        }

        throw new NotFoundHttpException('The requested page does not exist.');
    }
}
